package com.shexianyu.notes.common.utils;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * MD5加密工具类
 *
 * @author sxy
 * @version 1.0
 * @date 2021/2/27 14:58
 */
public class MD5Util {
    /**
     * 加密
     * 取字符串的特征值,明文转密文
     *
     * @param plainText
     * @return
     */
    public static String encrypt(String plainText) {
        String encryStr = null;
        if (plainText != null || !"".equals(plainText)) {
            try {
                //实例化MessageDigest，将md5的内容通过调用digest获取md5的byte值
                byte[] ret = MessageDigest.getInstance("md5").digest(plainText.getBytes());
                //将获取的byte数组值转为16进制的字符串
                String md5Code = new BigInteger(1, ret).toString(16);
                //获取的字符串不足32位的用“0”补齐
                for (int i = 0; i < 32 - md5Code.length(); i++) {
                    md5Code = "0" + md5Code;
                }
                encryStr = md5Code;
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
        return encryStr;
    }
}
